import React 			from 'react';
import PageTitle    	from 'component/pagetitle/index.jsx';
import MUtil        		from 'util/mm.jsx'
import Product         		from 'service/product-service.jsx'

const _util = new MUtil();
const _product = new Product();

class CategoryAdd extends React.Component{
	constructor(props){
		super(props);
		this.state = {
			categoryList	:	[],
			parentId		:	0,
			categoryName	:	''
		}
	}
	
	componentDidMount(){
		this.loadCateGoryList();
	}
	
	loadCateGoryList(){
		_product.getCategoryList()
				.then(res => {
					this.setState({
						categoryList :res
					});
				},errMsg => {
					_util.errorTips(errMsg);
				});
	}
	
	onValueChange(e){
		this.setState({
			[e.target.name]:e.target.value
		});
	}
	
	onAddCategory(){
		const categoryInfo = {
			categoryName	:	this.state.categoryName,
			parentId		:	parseInt(this.state.parentId)
		}
		const checkCategoryResult = _product.checkCategory(categoryInfo);
		if (checkCategoryResult.status) {
			_product.addCategory(categoryInfo)
					.then(res => {
						_util.successTips(res);
						this.props.history.push('/product-category/index');
					},errMsg => {
						_util.errorTips(errMsg);
					});
		}else{
			_util.errorTips(checkCategoryResult.msg);
		}
	}
	
	render(){
		return (
			
			<div id="page-wrapper">
				<PageTitle title='添加品类' />
				<div className="form-horizontal">
					<div className="form-group">
					<label  className="col-md-2 control-label">所属品类</label>
					<div className="col-md-4">
						<select className="form-control" name="parentId" onChange={e => {this.onValueChange(e)}}>
							<option>/所有</option>
							{
								this.state.categoryList.map((category,index) => {
									return( <option key={index} value={category.id}>/所有/{category.name}</option>)
								})
							}
						</select>
					</div>
					</div>
					<div className="form-group">
					<label  className="col-md-2 control-label">品类名称</label>
					<div className="col-md-4">
						<input type="text" className="form-control"  
											placeholder="请输入品类名称" 
											name='categoryName'
											onChange={e => {this.onValueChange(e)}}
						/>
					</div>
					</div>
					<div className="form-group">
						<div className="col-md-offset-2 col-md-10">
							<button type="submit" className="btn btn-primary" onClick={e => {this.onAddCategory()}}>提交</button>
						</div>
					</div>
				</div>
				
			</div>
			
		)
	}
}

export default CategoryAdd;